<template>
  <div class="">
    <el-form :model="postForm" :label-position="labelPosition" :rules="rules" ref="postForm" action="/tools/oss/uploadVideo">
      <el-form-item label="直播标题" prop="title">
        <el-input v-model="postForm.title" placeholder="请输入直播标题"></el-input>
      </el-form-item>
      <el-form-item label="主讲人" prop="teacher">
        <el-input v-model="postForm.teacher" placeholder="请输入主讲人"></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="start_time">
        <el-date-picker type="datetime" v-model="postForm.start_time" placeholder="请输入直播开始时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="end_time">
        <el-date-picker type="datetime" v-model="postForm.end_time" placeholder="请输入直播结束时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="缩略图地址" prop="thumbnail">
        <el-input v-model="postForm.thumbnail" placeholder="请输入缩略图地址"></el-input>
      </el-form-item>
      <el-form-item label="直播二维码图片" prop="live_imgae_url">
        <el-input v-model="postForm.live_imgae_url" placeholder="请输入直播二维码图片地址"></el-input>
      </el-form-item>
      <el-form-item label="回放视频地址" prop="live_video_url">
        <el-input v-model="postForm.live_video_url" placeholder="请输入回放视频地址"></el-input>
      </el-form-item>
      <el-form-item label="主讲人介绍" prop="teacher_introduction">
        <el-input type="textarea" v-model="postForm.teacher_introduction" placeholder="请输入主讲人介绍" :rows="3"></el-input>
      </el-form-item>
      <el-form-item class="leftPaddingChange">
        <el-button  type="primary" :disabled='preventSumit' v-loading='preventSumit' size="small" @click="submitForm('postForm')">保存</el-button>
        <el-button  size="small" @click="cancelChangeLesson" plain>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { validateURL } from '@/utils/validate'
  import { createLesson, modifyLesson, getLessonEnums } from '@/api/curriculum'
import { getTeacherList } from '@/api/teacher'
  import { getToken } from '@/utils/auth' // 验权
  import Tinymce from '@/components/Tinymce'
  import moment from 'moment'
  export default {
    name: 'add',
    props:{
      modifyData:{
        type:Object,
        required:false
      }
    },
    components: { Tinymce },
    data() {
      const validateRequire = (rule, value, callback) => {
        this.postForm[rule.field] = this.postForm[rule.field].trim()
        if (!value) {
          this.$message({
            message: this.i18n[rule.field] + '为必填项',
            type: 'error',
            duration: 1000
          })
          callback(new Error(this.i18n[rule.field] + '为必填项'))
        } else {
          callback()
        }
      }
      return {
        options:[],
        headers:{},
        teachers:[],
        fileList:[],
        statusText:['', '已上传'],
        labelPosition:'right', // 每一行 文字位置 element 配置
        isModify:false, // 新增 或者 修改
        preventSumit:false,
        uploadProgress:0,
        progressFactor:0.96,
        postForm:{
          title:'', // 标题
          teacher_introduction:'', // 老师介绍
          teacher:'', // 老师姓名
          start_time:'', // 开始时间
          end_time:'', // 结束时间
          thumbnail:'', // 缩略图
          live_imgae_url:'', // 图片地址
          live_video_url:'' // 视频地址
        },
        loading: false,
        i18n: {
          tag:'课程标签',
          lessonType:0,
          isFree:true,
          scheduleTime:'上课日期',
          teachingStartTime:'开始上课时间',
          teachingEndTime:'结束上课时间',
          lessonTopic:'上课主题',
          teacherId:'授课老师',
          // videoInfo:'视频信息',
          status:'课程状态',
          videoUrl:'上传视频'
        },
        rules: {
          tag: [
            { validator: validateRequire, trigger: 'blur' },
            { required: true, message: '请输入课程标签', trigger: 'blur' }
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          lessonType: [{ required: true, message: '请选录播-直播', trigger: 'change' }],
          isFree: [{ required: true, message: '请选课程类型', trigger: 'change' }],
          scheduleTime: [{ type: 'string', required: true, message: '请选择上课日期', trigger: 'change' }],
          teachingStartTime: [{ type: 'string', required: true, message: '请选择开始时间', trigger: 'change' }],
          teachingEndTime: [{ type: 'string', required: true, message: '请选择结束时间', trigger: 'change' }],
          lessonTopic:[
            { validator: validateRequire, trigger: 'blur' },
            { required: true, message: '请输入课程主题', validator: validateRequire, trigger: 'blur' },
            { min: 1, max: 30, message: '最多输入30个字符', trigger: 'blur' }
          ],
          teacherId: [{ required: true, message: '请至选择授课老师', trigger: 'change' }],
          videoUrl: [{ type: 'string', required: true, message: '请上传视频', trigger: 'change' }]
        }
      }
  },
    created() {
      // 是否是处于 修改状态
      this.isModify = !!this.modifyData
      //如果是 处于 修改状态 , 给 postForm 传值
      if(this.isModify){
        this.postForm = Object.assign({}, this.postForm, this.modifyData)
        this.postForm.videoUrl && (this.fileList = [{ url:this.postForm.videoUrl, name:this.postForm.videoUrl }])
        this.postForm.scheduleTime = this.formateDate(this.postForm.scheduleTime, 'YYYY-MM-DD')
        this.postForm.teachingStartTime = this.formateDate(this.postForm.teachingStartTime, 'HH:mm')
        this.postForm.teachingEndTime = this.formateDate(this.postForm.teachingEndTime, 'HH:mm')
      }

      // 获取 授课老师列表
      getTeacherList().then(response => {
        const { code, data, message } = response
        code == '0' && (this.teachers = this.teachers.concat(data)) || this.$message({ message, type:'error', duration:2000 })
      }
      )

      getLessonEnums().then(res => {
        const { data } = res
        this.options = data
      })
    },
    mounted() {
      // this.getSections();
      this.headers = { accessToken:getToken() }
  },
    methods: {
      lessonChange(targetFun, params, message) {
        targetFun(params).then(response => {
          const { code } = response
          if (code == 0) {
            this.$notify({
              title: '成功',
              message: message,
              type: 'success',
              duration: 1000
            })
            this.loading = false
            this.isModify && this.$emit('modifycomplete', true)
            this.$router.push('list')
          }
        }).catch(reject => {
          this.$emit('modifycomplete', false)
        })
      },
      modifyOrAddLesson() {
        const targetFun = this.isModify ? modifyLesson : createLesson
        this.postForm.tag = this.postForm.tag.trim()
        this.postForm.lessonTopic = this.postForm.lessonTopic.trim()
        const params = this.postForm
        const message = this.isModify ? '课程已保存' : '课程修改成功'
        this.lessonChange(targetFun, params, message)
      },
      submitForm() {
        this.$refs.postForm.validate(valid => {
          if (valid) {
            // if(!this.vaildateTime()|| !this.vaildateVedio()){return false}
            if(!this.vaildateTime()){ return false }
            this.loading = true
            this.modifyOrAddLesson()
          } else {
            return false
          }
        })
      },
      clearUpload() {
        if (!this.fileList.length) return false
        this.$refs.upload.clearFiles()
        this.fileList = []
      },
      handleUploadSuccess(response, file, fileList) {
        const { code, data:{ picUrlList }, message } = response
        if(code == 0){
          this.fileList = [{ name:picUrlList[0], url:picUrlList[0] }]
          this.uploadProgress = 100
          this.preventSumit = false
          setTimeout(() => { this.uploadProgress = 0 }, 1000)
        }else{
          this.$refs.upload.clearFiles()
          this.$notify({
            title: '失败',
            message: message,
            type: 'error',
            duration: 3000
          })
          this.preventSumit = false
        }
      },
      handProgress(file) {
        this.uploadProgress = parseInt(file.percent * this.progressFactor)
      },
      onBeforeUpload(file){
        this.progressFactor = Math.random(1)
        this.preventSumit = true
        //
        // if(!file.type.includes('android')){
        //   this.$notify({
        //       title: '失败',
        //     message: '请上传apk文件',
        //     type: 'error',
        //     duration: 2000
        //   })
        //   return false;
        // }else{
        //   return true;
        // }
      },
      handleRemove(file) {
        this.$refs.upload.clearFiles()
        this.fileList = []
      },
      vaildateTime() {
        const start = this.postForm.teachingStartTime
        const end = this.postForm.teachingEndTime
        if(!start || !end){ return false }
        const status = (start < end)
        !status && this.$message({
          message: '开始时间不能超过结束时间',
          type: 'error',
          duration: 2000
        })
        return status
      },
      vaildateVedio() {
        !this.fileList.length && this.$message({
          message: '请上传视频',
          type: 'error',
          duration: 2000
        })
        return this.fileList.length > 0
      },
      cancelChangeLesson() {
        this.$refs.postForm.resetFields()
        this.isModify && this.$emit('modifycomplete', true)
        this.isModify || this.$router.push('list')
      },
      formateDate(timeOrDate, type) {
        // timeStamp -- 'stamp'
        let result = ''
        switch(type){
          case 'stamp':
            result = new Date(timeOrDate).getTime()
            break
          default:
            result = moment(timeOrDate).format(type)
        }
        return result
      }
    },
    computed:{
      getLessonStatus() {
        if(this.fileList.length > 0) {
          this.postForm.videoUrl = this.fileList[0].url
          this.postForm.status = 1
        }else{
          this.postForm.videoUrl = ''
          this.postForm.status = 0
        }
        return this.statusText[this.postForm.status]
      },
      // trimTag (){
      //   this.postForm.tag = this.postForm.tag.trim()
      //   this.$forceUpdate()
      // },
      trimTag: {
        get: function() {
          return this.postForm.tag
        },
        set: function() {
          this.postForm.tag = this.postForm.tag.trim()
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import 'src/styles/mixin.scss';
  $left-offset:96px;
  .createPost-main-container{
    padding: 50px 0;
    @include clearfix;
  }
  .leftPaddingChange{
    button{
      min-width:100px;
    }
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  @import 'src/styles/mixin.scss';
  $border-color:#dcdfe6;
  $left-offset:96px;
  @mixin leftChange {
    padding-left:$left-offset;
    padding-top: 30px;
    box-sizing:content-box;
    @media screen and (max-width: 1205px){
      padding-left:0;
      box-sizing:border-box;
    }
  }
  .createPost-main-container{
    .readonlyInput{
      .el-input__inner{
        border:none;
        &:focus{
          border:none;
        }
      }
    }
    .el-time-panel.el-popper{
      box-sizing:content-box;
    }
    .el-radio__input.is-checked+.el-radio__label{
      color:#606266;
    }
    .el-upload{
      width:20%;
      margin-right:20px;
      min-width: 120px;
      .el-button--primary{
        width:100%;
      }
    }
    .videoBox,
    .leftPaddingChange{
      @include leftChange;
    }


  }
  .clearfix{
    float: left;
  }
  .el-form-item.is-success{
    .el-input__inner,
    .el-input__inner:focus,
    .el-textarea__inner,
    .el-textarea__inner:focus{
      border-color:$border-color;
    }
  }
  .videoInfoCotainer{
    .el-card{
      border:none;
    }
    .el-card__body{
      padding:0
    }
  }
</style>
